package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"strconv"
	"week2d/models/mysql"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

type Node struct {
	Conn     *websocket.Conn
	DataRead chan []byte
}

// 用户绑定
var UserClient map[int64]*Node = make(map[int64]*Node, 0)

func ClientSocket(c *gin.Context) {
	id1 := c.Query("userid1")
	id2 := c.Query("userid2")
	uid1, _ := strconv.Atoi(id1)
	uid2, _ := strconv.Atoi(id2)

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}
	node := &Node{
		Conn:     conn,
		DataRead: make(chan []byte, 50),
	}
	UserClient[int64(uid1)] = node
	sendMessage(node)
	readMessage(node, int64(uid2))
}

// 发送消息
func sendMessage(node *Node) {
	go func() {
		for {
			select {
			case data := <-node.DataRead:
				if err := node.Conn.WriteMessage(websocket.TextMessage, data); err != nil {
					log.Println(err)
					return
				}
			}
		}
	}()

}

// 获取消息
func readMessage(node *Node, userid int64) {
	for {
		_, mag, err := node.Conn.ReadMessage()
		if err != nil {
			log.Println(err)
			return
		}
		fmt.Println("消息", string(mag))
		//储存消息
		mysql.CreateInfo(string(mag))
		sendMessageTo(userid, mag)
	}
}

// 转发消息
func sendMessageTo(userid int64, mag []byte) {
	k, v := UserClient[userid]
	if v {
		k.DataRead <- mag
	}
}
